import { app } from '../../../scripts/app.js'

// 创建样式表
function createStylesheet() {
    const tag = 'sd-tagging-interactive-editor-stylesheet';
    let styleTag = document.head.querySelector(`#${tag}`);
    
    if (!styleTag) {
        styleTag = document.createElement('style');
        styleTag.type = 'text/css';
        styleTag.id = tag;
        styleTag.innerHTML = `
            .tag-editor-container {
                background: #2a2a2a;
                border: 1px solid #555;
                border-radius: 4px;
                padding: 10px;
                margin: 5px 0;
                font-family: monospace;
                font-size: 12px;
                color: #fff;
                display: flex;
                flex-direction: column;
                height: 400px;
            }
            
            .tag-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
                gap: 8px;
                margin: 10px 0;
                flex: 1;
                overflow-y: auto;
                padding: 8px;
                border: 1px solid #444;
                border-radius: 3px;
                background: #1e1e1e;
                align-content: start;
            }
            
            .tag-button {
                background: #4a4a4a;
                border: 1px solid #666;
                border-radius: 3px;
                padding: 6px 10px;
                color: #fff;
                cursor: pointer;
                font-size: 10px;
                text-align: center;
                transition: background-color 0.2s;
                height: auto;
                min-height: 40px;
                max-height: 60px;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                box-sizing: border-box;
                word-wrap: break-word;
                overflow: hidden;
                line-height: 1.2;
                white-space: pre-line;
            }
            
            .tag-button:hover {
                background: #5a5a5a;
                border-color: #777;
            }
            
            .tag-button.selected {
                background: #0066cc !important;
                border-color: #0088ff !important;
                box-shadow: 0 0 10px rgba(0, 102, 204, 0.5) !important;
                transform: scale(1.05);
                z-index: 10;
                position: relative;
            }
            
            .tag-controls {
                display: flex;
                gap: 5px;
                margin: 10px 0;
                flex-wrap: wrap;
                flex-shrink: 0;
            }
            
            .tag-input {
                background: #333;
                border: 1px solid #555;
                border-radius: 3px;
                padding: 5px;
                color: #fff;
                font-size: 11px;
                min-width: 120px;
            }
            
            .tag-btn {
                background: #0066cc;
                border: 1px solid #0088ff;
                border-radius: 3px;
                padding: 5px 10px;
                color: #fff;
                cursor: pointer;
                font-size: 11px;
                transition: background-color 0.2s;
            }
            
            .tag-btn:hover {
                background: #0088ff;
            }
            
            .tag-btn.danger {
                background: #cc3300;
                border-color: #ff4400;
            }
            
            .tag-btn.danger:hover {
                background: #ff4400;
            }

            .tag-btn.position {
                background: #6a4c93;
                border-color: #8b5cf6;
                min-width: 60px;
            }

            .tag-btn.position:hover {
                background: #8b5cf6;
            }

            /* 自定义滚动条样式 */
            .tag-grid::-webkit-scrollbar {
                width: 8px;
            }

            .tag-grid::-webkit-scrollbar-track {
                background: #333;
                border-radius: 4px;
            }

            .tag-grid::-webkit-scrollbar-thumb {
                background: #666;
                border-radius: 4px;
            }

            .tag-grid::-webkit-scrollbar-thumb:hover {
                background: #888;
            }
            
            .tag-info {
                color: #aaa;
                font-size: 10px;
                margin: 5px 0;
                flex-shrink: 0;
            }

            /* TextDisplay 样式 */
            .text-display-container {
                background: #2a2a2a;
                border: 1px solid #555;
                border-radius: 4px;
                padding: 15px;
                margin: 5px 0;
                font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
                color: #fff;
                max-height: 600px;
                overflow-y: auto;
            }

            .text-display-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 15px;
                padding-bottom: 10px;
                border-bottom: 1px solid #555;
                gap: 10px;
            }

            .copy-button {
                background: #4a90e2;
                border: 1px solid #357abd;
                border-radius: 4px;
                padding: 6px 12px;
                color: #fff;
                cursor: pointer;
                font-size: 11px;
                font-weight: bold;
                transition: all 0.2s ease;
                white-space: nowrap;
                min-width: 70px;
                height: 28px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .copy-button:hover {
                background: #357abd;
                border-color: #2968a3;
                transform: translateY(-1px);
            }

            .copy-button:active {
                transform: translateY(0);
            }

            .copy-button:disabled {
                cursor: not-allowed;
                opacity: 0.7;
                transform: none;
            }

            .copy-button.copy-success {
                background: #28a745;
                border-color: #1e7e34;
            }

            .copy-button.copy-error {
                background: #dc3545;
                border-color: #c82333;
            }

            /* NSFW标签样式 */
            .tag-button.nsfw-tag {
                border-width: 2px;
                font-weight: bold;
                position: relative;
            }

            .tag-button.nsfw-high {
                border-color: #ff4444;
                background: linear-gradient(135deg, #4a4a4a 0%, #5a2a2a 100%);
                box-shadow: 0 0 8px rgba(255, 68, 68, 0.3);
            }

            .tag-button.nsfw-medium {
                border-color: #ffaa00;
                background: linear-gradient(135deg, #4a4a4a 0%, #5a4a2a 100%);
                box-shadow: 0 0 8px rgba(255, 170, 0, 0.3);
            }

            .tag-button.nsfw-low {
                border-color: #ff8800;
                background: linear-gradient(135deg, #4a4a4a 0%, #5a3a2a 100%);
                box-shadow: 0 0 8px rgba(255, 136, 0, 0.3);
            }

            .tag-button.nsfw-tag:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            }

            .tag-button.nsfw-high:hover {
                box-shadow: 0 4px 12px rgba(255, 68, 68, 0.5);
            }

            .tag-button.nsfw-medium:hover {
                box-shadow: 0 4px 12px rgba(255, 170, 0, 0.5);
            }

            .tag-button.nsfw-low:hover {
                box-shadow: 0 4px 12px rgba(255, 136, 0, 0.5);
            }

            /* 标签翻译样式 */
            .tag-english {
                font-weight: bold;
                font-size: 10px;
                color: #fff;
            }

            .tag-chinese {
                font-size: 9px;
                color: #ccc;
                margin-top: 2px;
                font-style: italic;
            }

            .tag-button:hover .tag-chinese {
                color: #fff;
            }

            /* NSFW图例样式 */
            .nsfw-legend {
                background: #2a2a2a;
                border: 1px solid #555;
                border-radius: 4px;
                padding: 8px 12px;
                margin: 8px 0;
                display: flex;
                align-items: center;
                gap: 15px;
                font-size: 11px;
                color: #ccc;
            }

            .legend-title {
                font-weight: bold;
                color: #fff;
            }

            .legend-item {
                display: flex;
                align-items: center;
                gap: 4px;
                padding: 2px 6px;
                border-radius: 3px;
                font-size: 10px;
            }

            .legend-item.high {
                background: rgba(255, 68, 68, 0.2);
                border: 1px solid #ff4444;
            }

            .legend-item.medium {
                background: rgba(255, 170, 0, 0.2);
                border: 1px solid #ffaa00;
            }

            .legend-item.low {
                background: rgba(255, 136, 0, 0.2);
                border: 1px solid #ff8800;
            }

            .text-display-title {
                font-size: 14px;
                font-weight: bold;
                color: #4CAF50;
            }

            .text-display-stats {
                font-size: 11px;
                color: #aaa;
            }

            .text-display-content {
                background: #1e1e1e;
                border: 1px solid #444;
                border-radius: 3px;
                padding: 10px;
                font-size: 12px;
                line-height: 1.4;
                white-space: pre-wrap;
                word-wrap: break-word;
                max-height: 400px;
                overflow-y: auto;
            }

            .text-display-line-numbers {
                background: #1e1e1e;
                border: 1px solid #444;
                border-radius: 3px;
                padding: 10px;
                font-size: 12px;
                line-height: 1.4;
                max-height: 400px;
                overflow-y: auto;
            }

            .text-line {
                display: flex;
                margin: 0;
            }

            .line-number {
                color: #666;
                margin-right: 15px;
                min-width: 40px;
                text-align: right;
                user-select: none;
            }

            .line-content {
                flex: 1;
                white-space: pre-wrap;
                word-wrap: break-word;
            }

            .text-stats-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
                gap: 10px;
                margin-top: 10px;
                padding: 10px;
                background: #333;
                border-radius: 3px;
            }

            .stat-item {
                text-align: center;
                padding: 5px;
                background: #444;
                border-radius: 3px;
            }

            .stat-value {
                display: block;
                font-size: 16px;
                font-weight: bold;
                color: #4CAF50;
            }

            .stat-label {
                display: block;
                font-size: 10px;
                color: #aaa;
                margin-top: 2px;
            }
        `;
        document.head.appendChild(styleTag);
    }
}



// TextDisplay 扩展
app.registerExtension({
    name: 'SDTagging.TextDisplay',

    async beforeRegisterNodeDef(nodeType, nodeData) {
        if (nodeData?.name === 'TextDisplay') {

            // 创建样式表
            createStylesheet();

            // 链式回调函数
            function chainCallback(object, property, callback) {
                if (object == undefined) {
                    console.error("Tried to add callback to non-existant object");
                    return;
                }
                if (property in object) {
                    const callback_orig = object[property];
                    object[property] = function () {
                        const r = callback_orig.apply(this, arguments);
                        callback.apply(this, arguments);
                        return r;
                    };
                } else {
                    object[property] = callback;
                }
            }

            chainCallback(nodeType.prototype, "onNodeCreated", function () {
                // 创建DOM元素
                const element = document.createElement("div");
                element.className = "text-display-container";

                // 添加DOM widget
                this.textDisplay = this.addDOMWidget(nodeData.name, "TextDisplayWidget", element, {
                    serialize: false,
                    hideOnZoom: false,
                });

                // 初始化文本显示器
                this.initTextDisplay(element);

                // 设置节点大小
                this.setSize([600, 400]);
                this.resizable = true;

                // 监听节点执行完成事件
                chainCallback(this, "onExecuted", function(message) {
                    // 更新文本显示
                    if (message && message.text_content !== undefined) {
                        // 从数组中提取第一个元素
                        const textContent = Array.isArray(message.text_content) ? message.text_content[0] : message.text_content;
                        const textStats = Array.isArray(message.text_stats) ? message.text_stats[0] : message.text_stats;
                        const addLineNumbers = Array.isArray(message.add_line_numbers) ? message.add_line_numbers[0] : message.add_line_numbers;

                        this.updateTextDisplay(textContent, textStats, addLineNumbers);
                    }
                });
            });
        }
    }
});

// TextDisplay 方法扩展
app.registerExtension({
    name: 'SDTagging.TextDisplay.Methods',

    async beforeRegisterNodeDef(nodeType, nodeData) {
        if (nodeData?.name === 'TextDisplay') {

            nodeType.prototype.initTextDisplay = function(container) {
                this.currentText = "";
                this.currentStats = {};
                this.showLineNumbers = false;

                // 创建界面
                this.createTextDisplayUI(container);
            };

            nodeType.prototype.createTextDisplayUI = function(container) {
                container.innerHTML = `
                    <div class="text-display-header">
                        <div style="display: flex; flex-direction: column; flex: 1;">
                            <div class="text-display-title">📺 文本显示器</div>
                            <div class="text-display-stats" id="text-stats-summary">等待文本输入...</div>
                        </div>
                        <button class="copy-button" id="copy-text-btn" title="复制文本到剪切板">📋 复制</button>
                    </div>
                    <div class="text-display-content" id="text-content"></div>
                `;

                // 添加复制按钮事件监听器
                const copyBtn = container.querySelector('#copy-text-btn');
                if (copyBtn) {
                    copyBtn.addEventListener('click', () => {
                        this.copyTextToClipboard();
                    });
                }
            };

            nodeType.prototype.updateTextDisplay = function(textContent, textStats, showLineNumbers) {
                this.currentText = textContent || "";
                this.currentStats = textStats || {};
                this.showLineNumbers = showLineNumbers || false;

                const contentDiv = this.textDisplay.element.querySelector('#text-content');
                const statsSummary = this.textDisplay.element.querySelector('#text-stats-summary');

                // 更新文本内容
                if (this.showLineNumbers && this.currentText) {
                    this.displayTextWithLineNumbers(contentDiv);
                } else {
                    contentDiv.textContent = this.currentText;
                    contentDiv.className = 'text-display-content';
                }

                // 更新统计信息摘要
                if (this.currentStats && !this.currentStats.error) {
                    statsSummary.textContent = `${this.currentStats.char_count} 字符, ${this.currentStats.word_count} 单词, ${this.currentStats.line_count} 行`;
                } else if (this.currentStats.error) {
                    statsSummary.textContent = `错误: ${this.currentStats.error}`;
                } else {
                    statsSummary.textContent = '等待文本输入...';
                }
            };

            nodeType.prototype.displayTextWithLineNumbers = function(container) {
                const lines = this.currentText.split('\n');
                container.className = 'text-display-line-numbers';
                container.innerHTML = '';

                lines.forEach((line, index) => {
                    const lineDiv = document.createElement('div');
                    lineDiv.className = 'text-line';

                    const lineNumber = document.createElement('span');
                    lineNumber.className = 'line-number';
                    lineNumber.textContent = (index + 1).toString().padStart(3, ' ');

                    const lineContent = document.createElement('span');
                    lineContent.className = 'line-content';
                    lineContent.textContent = line;

                    lineDiv.appendChild(lineNumber);
                    lineDiv.appendChild(lineContent);
                    container.appendChild(lineDiv);
                });
            };

            nodeType.prototype.copyTextToClipboard = function() {
                if (!this.currentText) {
                    this.showCopyFeedback('❌ 没有文本可复制', false);
                    return;
                }

                // 使用现代的 Clipboard API
                if (navigator.clipboard && window.isSecureContext) {
                    navigator.clipboard.writeText(this.currentText).then(() => {
                        this.showCopyFeedback('✅ 已复制到剪切板', true);
                    }).catch(() => {
                        // 如果失败，尝试备用方法
                        this.fallbackCopyToClipboard();
                    });
                } else {
                    // 备用方法：使用传统的 execCommand
                    this.fallbackCopyToClipboard();
                }
            };

            nodeType.prototype.fallbackCopyToClipboard = function() {
                try {
                    // 创建临时文本区域
                    const textArea = document.createElement('textarea');
                    textArea.value = this.currentText;
                    textArea.style.position = 'fixed';
                    textArea.style.left = '-999999px';
                    textArea.style.top = '-999999px';
                    document.body.appendChild(textArea);

                    // 选择并复制
                    textArea.focus();
                    textArea.select();

                    const successful = document.execCommand('copy');
                    document.body.removeChild(textArea);

                    if (successful) {
                        this.showCopyFeedback('✅ 已复制到剪切板', true);
                    } else {
                        this.showCopyFeedback('❌ 复制失败', false);
                    }
                } catch (err) {
                    this.showCopyFeedback('❌ 复制失败', false);
                }
            };

            nodeType.prototype.showCopyFeedback = function(message, success) {
                const copyBtn = this.textDisplay.element.querySelector('#copy-text-btn');
                if (copyBtn) {
                    const originalText = copyBtn.textContent;
                    const originalClass = copyBtn.className;

                    // 显示反馈
                    copyBtn.textContent = message;
                    copyBtn.className = success ? 'copy-button copy-success' : 'copy-button copy-error';
                    copyBtn.disabled = true;

                    // 2秒后恢复原状
                    setTimeout(() => {
                        copyBtn.textContent = originalText;
                        copyBtn.className = originalClass;
                        copyBtn.disabled = false;
                    }, 2000);
                }
            };


        }
    }
});

// 扩展节点原型，添加标签编辑器初始化方法
app.registerExtension({
    name: 'SDTagging.InteractiveTextEditor.Methods',

    async beforeRegisterNodeDef(nodeType, nodeData) {
        if (nodeData?.name === 'SimpleTagEditor') {

            // 创建样式表
            createStylesheet();

            // 链式回调函数
            function chainCallback(object, property, callback) {
                if (object == undefined) {
                    console.error("Tried to add callback to non-existant object");
                    return;
                }
                if (property in object) {
                    const callback_orig = object[property];
                    object[property] = function () {
                        const r = callback_orig.apply(this, arguments);
                        callback.apply(this, arguments);
                        return r;
                    };
                } else {
                    object[property] = callback;
                }
            }

            chainCallback(nodeType.prototype, "onNodeCreated", function () {
                // 创建DOM元素
                const element = document.createElement("div");
                element.className = "tag-editor-container";

                // 添加DOM widget
                this.tagEditor = this.addDOMWidget("tag_editor", "div", element, {
                    serialize: false,
                    hideOnZoom: false,
                });

                // 获取必要的widgets
                const targetTagWidget = this.widgets.find(w => w.name === "target_tag");
                const newTagWidget = this.widgets.find(w => w.name === "new_tag");

                // 初始化标签编辑器
                this.initTagEditor(element, targetTagWidget, newTagWidget);

                // 设置节点大小
                this.setSize([600, 400]);
                this.resizable = true;
            });

            nodeType.prototype.initTagEditor = function(container, targetTagWidget, newTagWidget) {
                this.selectedTags = new Set();
                this.currentTags = [];

                // 创建界面
                this.createTagEditorUI(container, targetTagWidget, newTagWidget);

                // 监听节点执行完成事件
                const self = this;
                const originalOnExecuted = this.onExecuted;
                this.onExecuted = function(message) {
                    if (originalOnExecuted) {
                        originalOnExecuted.call(this, message);
                    }

                    // 更新标签显示
                    if (message && message.tags_list) {
                        // 从数组中提取数据
                        const tagsList = Array.isArray(message.tags_list) ? message.tags_list[0] : message.tags_list;
                        const tagsNsfwInfo = Array.isArray(message.tags_nsfw_info) ? message.tags_nsfw_info[0] : (message.tags_nsfw_info || {});
                        const tagTranslations = Array.isArray(message.tag_translations) ? message.tag_translations[0] : (message.tag_translations || {});

                        self.updateTagDisplay(tagsList, tagsNsfwInfo, tagTranslations);
                    }

                    // 更新文件列表和选中文件
                    if (message && message.file_list) {
                        const fileList = Array.isArray(message.file_list) ? message.file_list[0] : message.file_list;
                        self.updateFileList(fileList);
                    }

                    // 更新选中文件
                    if (message && message.current_file !== undefined) {
                        const currentFile = Array.isArray(message.current_file) ? message.current_file[0] : message.current_file;
                        self.selectedFile = currentFile || "所有文件";
                        self.updateFileInfo();

                        // 更新下拉选择
                        const fileSelect = self.tagEditor.element.querySelector('#file-select');
                        if (fileSelect) {
                            fileSelect.value = self.selectedFile;
                        }
                    }
                };
            };
            
            nodeType.prototype.createTagEditorUI = function(container, targetTagWidget, newTagWidget) {
                container.innerHTML = `
                    <div class="tag-info">🏷️ 交互式标签编辑器</div>
                    <div class="tag-controls">
                        <select class="tag-input" id="file-select" style="width: 200px;">
                            <option value="所有文件">所有文件</option>
                        </select>
                        <input type="text" class="tag-input" id="new-tag-input" placeholder="输入新标签...">
                        <button class="tag-btn position" id="position-toggle-btn" title="切换添加位置">📍 末尾</button>
                        <button class="tag-btn" id="add-tag-btn">添加标签</button>
                    </div>
                    <div class="tag-controls">
                        <button class="tag-btn danger" id="delete-selected-btn">删除选中</button>
                        <button class="tag-btn" id="clear-selection-btn">清除选择</button>
                    </div>
                    <div class="tag-info" id="tag-count">标签数量: 0 | 点击选择，双击编辑，支持多选</div>
                    <div class="nsfw-legend" id="nsfw-legend" style="display: none;">
                        <span class="legend-title">🔍 标记说明：</span>
                        <span class="legend-item high">🔴 高风险</span>
                        <span class="legend-item medium">🟡 中风险</span>
                        <span class="legend-item low">🟠 低风险</span>
                    </div>
                    <div class="tag-grid" id="tag-grid"></div>
                `;
                
                // 绑定事件
                this.bindTagEditorEvents(container, targetTagWidget, newTagWidget);
            };
            
            nodeType.prototype.bindTagEditorEvents = function(container, targetTagWidget, newTagWidget) {
                const fileSelect = container.querySelector('#file-select');
                const newTagInput = container.querySelector('#new-tag-input');
                const positionToggleBtn = container.querySelector('#position-toggle-btn');
                const addTagBtn = container.querySelector('#add-tag-btn');

                const deleteSelectedBtn = container.querySelector('#delete-selected-btn');
                const clearSelectionBtn = container.querySelector('#clear-selection-btn');

                // 状态变量
                this.addToFront = false;
                this.selectedFile = "所有文件";
                this.fileList = [];

                // 文件选择事件
                fileSelect.addEventListener('change', () => {
                    this.selectedFile = fileSelect.value;

                    // 设置选中文件
                    const selectedFileWidget = this.widgets.find(w => w.name === "selected_file");
                    if (selectedFileWidget) {
                        selectedFileWidget.value = this.selectedFile;
                    }

                    // 触发节点执行以切换文件
                    app.queuePrompt(0, 1);
                });

                // 位置切换按钮
                positionToggleBtn.addEventListener('click', () => {
                    this.addToFront = !this.addToFront;
                    positionToggleBtn.textContent = this.addToFront ? '📍 开头' : '📍 末尾';
                    positionToggleBtn.title = this.addToFront ? '当前：添加到开头，点击切换到末尾' : '当前：添加到末尾，点击切换到开头';
                });

                // 添加标签
                const addTag = () => {
                    const newTag = newTagInput.value.trim();
                    if (newTag) {
                        // 根据位置设置标签值，使用特殊前缀标识位置
                        const tagWithPosition = this.addToFront ? `__FRONT__${newTag}` : newTag;
                        newTagWidget.value = tagWithPosition;

                        // 设置操作类型
                        const operationWidget = this.widgets.find(w => w.name === "operation");
                        if (operationWidget) {
                            operationWidget.value = "添加标签";
                        }

                        // 设置选中文件
                        const selectedFileWidget = this.widgets.find(w => w.name === "selected_file");
                        if (selectedFileWidget) {
                            selectedFileWidget.value = this.selectedFile;
                        }

                        newTagInput.value = '';

                        // 触发节点执行
                        app.queuePrompt(0, 1);
                    }
                };

                addTagBtn.addEventListener('click', addTag);
                newTagInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        addTag();
                    }
                });
                
                // 删除选中标签
                deleteSelectedBtn.addEventListener('click', () => {
                    if (this.selectedTags.size > 0) {
                        const tagsToDelete = Array.from(this.selectedTags);
                        targetTagWidget.value = tagsToDelete.join(',');
                        // 设置操作类型
                        const operationWidget = this.widgets.find(w => w.name === "operation");
                        if (operationWidget) {
                            operationWidget.value = "删除标签";
                        }

                        // 设置选中文件
                        const selectedFileWidget = this.widgets.find(w => w.name === "selected_file");
                        if (selectedFileWidget) {
                            selectedFileWidget.value = this.selectedFile;
                        }

                        this.selectedTags.clear();

                        // 触发节点执行
                        app.queuePrompt(0, 1);
                    }
                });
                
                // 清除选择
                clearSelectionBtn.addEventListener('click', () => {
                    this.selectedTags.clear();
                    this.updateTagSelection();
                });
            };
            
            nodeType.prototype.updateTagDisplay = function(tags, nsfwInfo, translations) {
                this.currentTags = tags || [];
                this.nsfwInfo = nsfwInfo || {};
                this.tagTranslations = translations || {};
                const tagGrid = this.tagEditor.element.querySelector('#tag-grid');
                const tagCount = this.tagEditor.element.querySelector('#tag-count');
                const nsfwLegend = this.tagEditor.element.querySelector('#nsfw-legend');

                // 检查是否有NSFW标签
                const hasNsfwTags = this.currentTags.some(tag => {
                    const tagInfo = this.nsfwInfo[tag];
                    return tagInfo && tagInfo.is_nsfw;
                });

                // 显示或隐藏图例
                if (nsfwLegend) {
                    nsfwLegend.style.display = hasNsfwTags ? 'flex' : 'none';
                }

                const selectedCount = this.selectedTags.size;
                if (selectedCount > 0) {
                    tagCount.textContent = `标签数量: ${this.currentTags.length} | 已选择: ${selectedCount} 个标签`;
                } else {
                    tagCount.textContent = `标签数量: ${this.currentTags.length} | 点击选择，双击编辑，支持多选`;
                }

                tagGrid.innerHTML = '';
                this.currentTags.forEach((tag) => {
                    const tagButton = document.createElement('div');
                    tagButton.className = 'tag-button';

                    // 获取翻译
                    const translation = this.tagTranslations[tag];

                    // 检查NSFW状态并添加标记
                    const tagInfo = this.nsfwInfo[tag];
                    let tooltipText = tag;

                    // 创建标签内容
                    tagButton.innerHTML = '';

                    // 英文标签部分
                    const englishPart = document.createElement('div');
                    englishPart.className = 'tag-english';

                    if (tagInfo && tagInfo.is_nsfw) {
                        englishPart.textContent = `${tagInfo.marker} ${tag}`;
                        tagButton.classList.add('nsfw-tag');
                        tagButton.classList.add(`nsfw-${tagInfo.severity}`);
                        tooltipText = `⚠️ ${tagInfo.category} (${tagInfo.severity})`;
                    } else {
                        englishPart.textContent = tag;
                    }

                    tagButton.appendChild(englishPart);

                    // 中文翻译部分
                    if (translation) {
                        const chinesePart = document.createElement('div');
                        chinesePart.className = 'tag-chinese';
                        chinesePart.textContent = translation;
                        tagButton.appendChild(chinesePart);
                        tooltipText += `\n中文: ${translation}`;
                    }

                    tagButton.title = tooltipText;

                    tagButton.dataset.tag = tag;
                    
                    // 单击选择/取消选择
                    let clickTimeout;
                    tagButton.addEventListener('click', (e) => {
                        // 清除之前的超时
                        if (clickTimeout) {
                            clearTimeout(clickTimeout);
                        }

                        // 立即提供视觉反馈
                        const isCurrentlySelected = this.selectedTags.has(tag);
                        if (isCurrentlySelected) {
                            tagButton.classList.remove('selected');
                        } else {
                            tagButton.classList.add('selected');
                        }

                        // 设置延迟执行，避免与双击冲突
                        clickTimeout = setTimeout(() => {
                            if (this.selectedTags.has(tag)) {
                                this.selectedTags.delete(tag);
                            } else {
                                this.selectedTags.add(tag);
                            }
                            this.updateTagSelection();
                        }, 200); // 200ms延迟
                    });

                    // 双击编辑
                    tagButton.addEventListener('dblclick', (e) => {
                        e.preventDefault();
                        e.stopPropagation();

                        // 取消单击的延迟执行
                        if (clickTimeout) {
                            clearTimeout(clickTimeout);
                            clickTimeout = null;
                        }

                        // 恢复正确的选中状态
                        if (this.selectedTags.has(tag)) {
                            tagButton.classList.add('selected');
                        } else {
                            tagButton.classList.remove('selected');
                        }

                        this.editTagInline(tagButton, tag);
                    });
                    
                    tagGrid.appendChild(tagButton);
                });
                
                this.updateTagSelection();
            };
            
            nodeType.prototype.updateTagSelection = function() {
                const tagButtons = this.tagEditor.element.querySelectorAll('.tag-button');
                const tagCount = this.tagEditor.element.querySelector('#tag-count');

                tagButtons.forEach(button => {
                    if (this.selectedTags.has(button.dataset.tag)) {
                        button.classList.add('selected');
                    } else {
                        button.classList.remove('selected');
                    }
                });

                // 更新计数显示
                const selectedCount = this.selectedTags.size;
                if (selectedCount > 0) {
                    tagCount.textContent = `标签数量: ${this.currentTags.length} | 已选择: ${selectedCount} 个标签`;
                } else {
                    tagCount.textContent = `标签数量: ${this.currentTags.length} | 点击选择，双击编辑，支持多选`;
                }
            };

            nodeType.prototype.updateFileList = function(fileList) {
                this.fileList = fileList || [];
                const fileSelect = this.tagEditor.element.querySelector('#file-select');

                if (fileSelect) {
                    // 清空现有选项
                    fileSelect.innerHTML = '';

                    // 添加文件选项
                    this.fileList.forEach(file => {
                        const option = document.createElement('option');
                        option.value = file;
                        option.textContent = file;
                        fileSelect.appendChild(option);
                    });

                    // 设置当前选中的文件
                    if (this.selectedFile) {
                        fileSelect.value = this.selectedFile;
                    }
                }

                // 更新文件信息显示
                this.updateFileInfo();
            };

            nodeType.prototype.updateFileInfo = function() {
                const fileInfo = this.tagEditor.element.querySelector('#file-info');
                if (fileInfo) {
                    fileInfo.textContent = `当前选择: ${this.selectedFile || "所有文件"}`;
                }
            };

            nodeType.prototype.editTagInline = function(tagButton, originalTag) {
                // 保存原始内容
                const originalHTML = tagButton.innerHTML;

                // 创建输入框
                const input = document.createElement('input');
                input.type = 'text';
                input.value = originalTag;
                input.className = 'tag-edit-input';
                input.style.cssText = `
                    width: 100%;
                    height: 100%;
                    border: none;
                    background: #0066cc;
                    color: white;
                    font-size: 11px;
                    padding: 0;
                    margin: 0;
                    text-align: center;
                    border-radius: 3px;
                `;

                // 替换按钮内容
                tagButton.innerHTML = '';
                tagButton.appendChild(input);
                tagButton.classList.add('editing');

                // 选中文本
                input.focus();
                input.select();

                // 保存编辑
                const saveEdit = () => {
                    const newTag = input.value.trim();
                    if (newTag && newTag !== originalTag) {
                        // 执行修改操作
                        this.modifyTag(originalTag, newTag);
                    } else {
                        // 恢复原始内容
                        tagButton.innerHTML = originalHTML;
                        tagButton.classList.remove('editing');
                    }
                };

                // 取消编辑
                const cancelEdit = () => {
                    tagButton.innerHTML = originalHTML;
                    tagButton.classList.remove('editing');
                };

                // 事件监听
                input.addEventListener('blur', saveEdit);
                input.addEventListener('keydown', (e) => {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        saveEdit();
                    } else if (e.key === 'Escape') {
                        e.preventDefault();
                        cancelEdit();
                    }
                });
            };

            nodeType.prototype.modifyTag = function(originalTag, newTag) {
                const targetTagWidget = this.widgets.find(w => w.name === "target_tag");
                const newTagWidget = this.widgets.find(w => w.name === "new_tag");

                if (targetTagWidget && newTagWidget) {
                    targetTagWidget.value = originalTag;
                    newTagWidget.value = newTag;

                    // 设置操作类型
                    const operationWidget = this.widgets.find(w => w.name === "operation");
                    if (operationWidget) {
                        operationWidget.value = "修改标签";
                    }

                    // 设置选中文件
                    const selectedFileWidget = this.widgets.find(w => w.name === "selected_file");
                    if (selectedFileWidget) {
                        selectedFileWidget.value = this.selectedFile;
                    }

                    // 触发节点执行
                    app.queuePrompt(0, 1);
                }
            };
        }
    }
});
